#!/bin/bash
# vim: ts=2 syn=sh

# 1. Load kernel mods
# 2. Load bootnet/sshd
# 3. Get passwd
# 4. Open devices(md,enclayer) , not mount them 
# 5. make_key; mkswap
# 6. Mount root, cp /etc/nemonico to initram  and do the descriptors 

PATH=/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin ; export PATH
LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib ; export LD_LIBRARY_PATH

set -eE

_chk_err ()
{
		local count
		echo " ERROR:  6 beeps/seconds then reboot."
  	while true; do
  		echo -ne '\a'
  		sleep 1
			count=$(($count+1))
  		test $count -eq 6 && reboot
  	done
}

trap '_chk_err' ERR

/bin/mount -t proc none /proc 
/bin/mount -n -t sysfs none /sys 
mdev -s
rm -f /etc/mtab
ln -s /proc/mounts /etc/mtab

. /etc/scripts/env 
. /etc/scripts/utils.fn 

luks="cryptsetup"; export luks

setlogcons 12

echo "Basic environment loaded ..."

# /proc/cmdline
if [ "`cat /proc/cmdline|grep -i rescue`" ]; then
	echo ""
	echo " RESCUE MODE CALLED "; sleep 1
	echo ""
	cat /etc/files/console_message
	/bin/bash
fi 

# source root and boot descriptor
unset MOUNTPOINT
for d in `ls /nemonico/MOUNTPOINT.*|grep -vE ".bck|.tmp"$ `; do
	. $d
	if [ "$MOUNTPOINT" = "/" ]; then
		root_desc=$d
		break
	else
		continue
	fi
	echo " ERROR: /nemonico/MOUNTPOINT.root is not present, or is not linked from"
	echo " 	the MOUNTPOINT descriptor holding the root device configuration. "
	echo " "
	/bin/bash
done

if [ -f /nemonico/BOOT ]; then
	. /nemonico/BOOT
else
	echo ""
	echo " === Could not find /nemonico/BOOT, needed for booting from network. "
	echo "     Will continue with CONSOLE ONLY routines ..."
	echo ""
fi

# gather vars
. /nemonico/MOUNTPOINT.root
hostname=`__get_desc_val /nemonico/NETWORK HOSTNAME`
root_enclayer="`_is_on_enclayer /nemonico/MOUNTPOINT.root`"
if [ "`__get_desc_val /nemonico/MOUNTPOINT.root LV_NAME`" ]; then
	root_lv="`__get_desc_val /nemonico/MOUNTPOINT.root LV_NAME`"
	root_vg="`__get_desc_val /nemonico/MOUNTPOINT.root VG_NAME`"
else
	root_dev="`__get_desc_val /nemonico/MOUNTPOINT.root DEVICE`"	
fi
	
# device modules
[ -x /load_kernel_modules ] &&  . /load_kernel_modules
mdev -s

# start interface and sshd
if [ "$BOOT_NET_ENABLE" = "Y" ]; then
		echo "BOOT Network ..."
		if [ -f /nemonico/keys/authorized_keys ]; then
			${BOOT_NET_SCRIPT:-/etc/scripts/network.wired} start
		else
			echo ""
			echo " === Could not start pre-boot network, missing: "
			echo "     /root/.ssh/authorized_keys. continuing... "
			echo ""
			BOOT_NET_ENABLE="N"
		fi
		cat /tmp/interface	
fi

# get passphrase
echo -e "\n5 Seconds Wait ...\n"
sleep 5
mdev -s
echo -e "\n\n\n\n"
( /getpassword_console.sh < /dev/console > /dev/console 2>&1 || : ) & 1>/dev/null
while [ ! -s $vp_pass ]; do
		sleep 1
done

# Open root
##### Open parents descriptors
mdev -s
unset str
for r in `__get_parents /nemonico/MOUNTPOINT.root`; do
	str="$r $str"	
done
echo "$str" > /tmp/reverse_parent_list_root
for d in `cat /tmp/reverse_parent_list_root`; do
				# if lvm 
				# if md
				# if enclayer
				DEVICES=""
				PV_DEVICES=""
				ALGO=""
				. $d
				mdev -s
				if [ "$VG_NAME" -a "$PV_DEVICES" ]; then
					echo " === ROOT-LVM ..."
					vgscan --mknodes --ignorelockingfailure
					sleep 10 
					vgchange -ay --ignorelockingfailure
				elif [ "$DEVICES" ]; then
					echo " === ROOT-MD ..."
					mdadm --examine --scan --config=partitions > /etc/mdadm.conf
					mdadm -A -m dev /dev/`__strip_bdot $d`
				elif [ "$ALGO" ]; then
					echo " === ROOT-LUKS ..."
					_luks_open_dev $d
				fi
done
echo "$str" > /tmp/reverse_parent_list_done

# check the root fs
. /nemonico/MOUNTPOINT.root
mk_fstab  /nemonico/MOUNTPOINT.root
echo " Checking root filesystem ... "
if [ "$root_lv" ]; then	
	fsck -C -a /dev/$root_vg/$root_lv
	mount -o ro -t $FORMAT /dev/$root_vg/$root_lv /mnt/root
elif [ "$root_dev" ]; then
	fsck -C -a $root_dev
	mount -o ro -t $FORMAT  $root_dev /mnt/root
fi

# up to luks Open devices from /mnt/root/etc/nemonico
##### Open parents descriptors
unset r d dd
for d in `ls /mnt/root/etc/nemonico/MOUNTPOINT.*|grep -viE ".tmp$|.bck$|~$|.root$|.boot$"`; do
	# reverse output
	unset str
	for r in `__get_parents $d`; do
		str="$r $str"
	done
	# save it for comparing
	echo "$str" > /tmp/reverse_parent_list_current
	for dd in $(</tmp/reverse_parent_list_current) ; do
		DEVICE=""
		VG_NAME=""
		PV_DEVICES=""
		DEVICES=""
		PV_DEVICES=""
		ALGO=""
		# dont reopen
		if grep -q "`basename $dd`" /tmp/reverse_parent_list_done ; then
			continue
		fi
		. $dd
		mdev -s
		if [ "$VG_NAME" -a "$PV_DEVICES" ]; then
			echo " === LVM-[`basename $dd`] ..."
			vgscan --mknodes --ignorelockingfailure
			sleep 10 
			vgchange -ay --ignorelockingfailure
		elif [ "$DEVICES" ]; then
			echo " === MD-[`basename $dd`] ..."
			mdadm -Ac partitions -m dev /dev/`__strip_bdot $dd`
		elif [ "$ALGO" ]; then
			echo " === LUKS-[`basename $dd`] ..."
			_luks_open_dev $dd
		fi
	done
	echo "$str" >> /tmp/reverse_parent_list_done
done

# stop network
kill -9 `cat /tmp/getpassword_console.sh.pid` 2>/dev/null || :
if [ "$BOOT_NET_ENABLE" = "Y" ]; then
				${BOOT_NET_SCRIPT:-/etc/scripts/network.wired} stop
				[ -f /tmp/getpassword_remote.sh.pid ] && \
					kill -9 `cat /tmp/getpassword_remote.sh.pid` 2>/dev/null || :
fi

# cp devs
mdev -s
trap - ERR
mount -o remount,rw,sync /mnt/root
# see /etc/rc.d/rc.S
mkdir -p -m 700 /mnt/root/etc/lvm/backup 
# starting the movement
mount -o remount,ro /mnt/root
umount /proc
umount /sys
set +eE
echo "###############################"
echo "### NEMONICO [Fenix.Funk.5] ###"
echo "###############################"
exec switch_root /mnt/root /sbin/init $@
